import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, SafeAreaView, ActivityIndicator, FlatList, TouchableOpacity, Image, Dimensions, RefreshControl, Modal, TextInput, ScrollView, Animated, Alert, Platform, PermissionsAndroid } from 'react-native';
import Header from '../../../../components/Header';
import { getIQCBodyList, IQCBodyItem, execIQC } from './api';
import { launchCamera, launchImageLibrary, ImagePickerResponse } from 'react-native-image-picker';
import xIcon from '../../../../assets/x.png';
import xiangjiIcon from '../../../../assets/xiangji.png';
import jiahao from '../../../../assets/jiahao.png';
import saoma from '../../../../assets/saoma.png';
import xiala from '../../../../assets/xiala.png';
import { request } from '../../../../services/request';
import CustomQRScanner from '../../../../components/CustomQRScanner';
import { Toast } from '@ant-design/react-native';

// 缺陷项类型
interface DefectItem {
    id: string;
    defect_name: string;
}

// 搜索缺陷接口响应类型
interface SearchDefectResponse {
    code: number;
    msg: string;
    data: {
        records: DefectItem[];
        total: number;
        size: number;
        current: number;
        pages: number;
    };
}

interface IqcDetailProps {
    onNavigateToLogin?: () => void;
    onBackPress?: () => void;
    iqc_num?: string;
}

const IqcDetail: React.FC<IqcDetailProps> = ({ onNavigateToLogin, onBackPress, iqc_num }) => {
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<IQCBodyItem[]>([]);
    const [refreshing, setRefreshing] = useState(false);

    // 从全局变量获取iqc_num
    const currentIqcNum = iqc_num || (global as any).iqcDetailData?.iqc_num;

    // 图片全屏显示相关状态
    const [imageModalVisible, setImageModalVisible] = useState(false);
    const [selectedImage, setSelectedImage] = useState<string>('');

    // 图片上传相关状态，key为卡片id
    const [uploadedImagesMap, setUploadedImagesMap] = useState<{ [key: string]: string[] }>({});

    // 模态框相关状态
    const [modalVisible, setModalVisible] = useState(false);
    const [scanModalVisible, setScanModalVisible] = useState(false);
    const [materialCode, setMaterialCode] = useState('');
    const [selectedResult, setSelectedResult] = useState(1); // 1: 合格, 2: 报废
    const [defectList, setDefectList] = useState<DefectItem[]>([]);
    const [selectedDefect, setSelectedDefect] = useState<string>('');
    const [defectDropdownVisible, setDefectDropdownVisible] = useState(false);
    const [defectArrowRotation] = useState(new Animated.Value(0));

    // 已添加的物料列表，key为卡片id
    const [selectedMaterialsMap, setSelectedMaterialsMap] = useState<{
        [key: string]: Array<{
            materialCode: string;
            result: number;
            defectId: string;
            defectName: string;
        }>
    }>({});
    // 当前操作的卡片id
    const [currentCardId, setCurrentCardId] = useState<string | null>(null);

    // 在组件顶部添加新的state
    const [defectSelectModalVisible, setDefectSelectModalVisible] = useState(false);
    const [defectSearch, setDefectSearch] = useState('');

    // 获取缺陷列表
    const fetchDefectList = async () => {
        try {
            const params = {
                current: 1,
                size: -1
            };

            console.log('=== 搜索缺陷接口请求数据 ===');
            console.log('请求参数:', params);
            console.log('======================');

            const response = await request('app/qms/searchDefect', {
                method: 'POST',
                body: JSON.stringify(params),
            }) as SearchDefectResponse;

            console.log('=== 搜索缺陷接口返回数据 ===');
            console.log('响应状态:', response.code);
            console.log('响应消息:', response.msg);
            console.log('响应数据:', response);
            console.log('======================');

            setDefectList(response.data?.records || []);
        } catch (error: any) {
            console.error('=== 搜索缺陷接口调用失败 ===');
            console.error('错误信息:', error.message);
            console.error('错误详情:', error);
            console.error('======================');
        }
    };

    // 切换故障原因下拉框显示状态
    const toggleDefectDropdown = () => {
        const toValue = defectDropdownVisible ? 0 : 1;
        setDefectDropdownVisible(!defectDropdownVisible);
        Animated.timing(defectArrowRotation, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };



    // 模态框确认按钮处理
    const handleModalConfirm = () => {
        if (!materialCode.trim()) {
            console.log('物料编码不能为空');
            // setModalVisible(false);
            Toast.info('物料编码不能为空', 1);
            return;
        }
        if (selectedResult !== 1 && !selectedDefect) {
            console.log('请选择故障原因');
            Toast.info('请选择故障原因', 1);
            return;
        }
        // 获取选中的故障原因名称
        const selectedDefectItem = defectList.find(d => d.id === selectedDefect);
        const defectName = selectedDefectItem?.defect_name || '';
        // 添加到当前卡片的已选择物料列表
        if (currentCardId) {
            setSelectedMaterialsMap(prev => {
                const prevList = prev[currentCardId!] || [];
                return {
                    ...prev,
                    [currentCardId]: [
                        ...prevList,
                        {
                            materialCode: materialCode,
                            result: selectedResult,
                            defectId: selectedResult === 1 ? '' : selectedDefect,
                            defectName: selectedResult === 1 ? '' : defectName,
                        }
                    ]
                };
            });
        }
        // 关闭模态框并重置状态
        setModalVisible(false);
        setMaterialCode('');
        setSelectedResult(1);
        setSelectedDefect('');
        setCurrentCardId(null);
    };

    // 添加物料相关状态（可后续完善）
    const handleImageUpload = (cardId: string) => {
        const options = {
            mediaType: 'photo' as const,
            includeBase64: false,
            maxHeight: 2000,
            maxWidth: 2000,
        };
        Alert.alert(
            '选择图片来源',
            '请选择图片来源',
            [
                { text: '取消', style: 'cancel' },
                { text: '拍照', onPress: () => launchCamera(options, (res) => handleImageResponse(res, cardId)) },
                { text: '从相册选择', onPress: () => launchImageLibrary(options, (res) => handleImageResponse(res, cardId)) },
            ]
        );
    };
    const handleImageResponse = (response: ImagePickerResponse, cardId: string) => {
        if (response.didCancel) {
        } else if (response.errorCode) {
        } else if (response.assets && response.assets[0]) {
            const imageUri = response.assets[0].uri;
            if (imageUri) {
                setUploadedImagesMap(prev => {
                    const prevList = prev[cardId] || [];
                    return { ...prev, [cardId]: [...prevList, imageUri] };
                });
            }
        }
    };

    // 获取IQC详情数据
    const fetchIQCBodyList = async () => {
        if (!currentIqcNum) {
            console.error('IQC单号为空');
            return;
        }

        setLoading(true);
        try {
            const params = {
                iqc_num: currentIqcNum
            };

            const response = await getIQCBodyList(params);
            setData(response.data);
        } catch (error: any) {
            console.error('=== IQC详情接口调用失败 ===');
            console.error('错误信息:', error.message);
            console.error('错误详情:', error);
            console.error('======================');
        } finally {
            setLoading(false);
        }
    };

    // 页面加载时调用接口
    useEffect(() => {
        fetchIQCBodyList();
    }, []);

    // 下拉刷新
    const handleRefresh = async () => {
        setRefreshing(true);
        await fetchIQCBodyList();
        setRefreshing(false);
    };

    // 确认按钮处理
    const handleConfirm = async (item: IQCBodyItem) => {
        const materials = selectedMaterialsMap[item.id] || [];
        if (materials.length === 0) {
            Toast.info('请先添加物料', 1);
            return;
        }
        // 统计数量
        const unqualified_quantity = materials.filter(m => m.result === 2).length;
        const fatal_quantity = materials.filter(m => m.result === 3).length;
        const accept_quantity = materials.filter(m => m.result === 5).length;
        // 组装 product_list
        const product_list = materials.map(material => ({
            result: material.result,
            defect_id: material.result === 1 ? '' : material.defectId,
            defect_name: material.result === 1 ? '' : material.defectName,
            defect_num: '', // 如有defect_num可补充
            extend_list: [],
        }));
        // 组装 pic_list
        const pic_list = (uploadedImagesMap[item.id] || []).map(link => ({ link }));
        // 组装最终数据
        const params = [{
            id: item.id,
            unqualified_quantity,
            fatal_quantity,
            rework_quantity: 0,
            accept_quantity,
            header_id: item.header_id,
            check_type: 1,
            product_list,
            pic_list,
        }];
        try {
            const res = await execIQC(params);
            if (res && res.msg) {
                Toast.info(res.msg, 1);
            }
            if (res && res.code === 200) {
                fetchIQCBodyList();
            }
        } catch (error) {
            // 错误已在api.ts中打印
        }
    };

    // 渲染列表项
    const renderItem = ({ item }: { item: IQCBodyItem }) => {
        // 统计数量
        const materials = selectedMaterialsMap[item.id] || [];
        const unqualifiedCount = materials.filter(m => m.result === 2).length;
        const fatalCount = materials.filter(m => m.result === 3).length;
        const acceptCount = materials.filter(m => m.result === 5).length;
        const isFinished = item.state === 3;

        return (
            <View style={styles.card}>
                {/* 检验详情部分 */}
                <View style={styles.inspectionDetails}>
                    <View style={styles.detailColumn}>
                        <Text style={styles.detailTitle}>检验项目</Text>
                        <Text style={styles.detailValue}>{item.prj_name || item.product_name || '无'}</Text>
                    </View>
                    <View style={styles.detailColumn}>
                        <Text style={styles.detailTitle}>检验单位</Text>
                        <Text style={styles.detailValue}>{item.unit_kk || '无'}</Text>
                    </View>
                    <View style={styles.detailColumn}>
                        <Text style={styles.detailTitle}>检验标准</Text>
                        <Text style={styles.detailValue}>{item.test_standard || '无'}</Text>
                    </View>
                </View>
                {/* 检验结果部分 */}
                <View style={styles.resultsContainer}>
                    <View style={styles.resultBox}>
                        <Text style={styles.resultTitle}>不合格</Text>
                        <Text style={styles.resultNumber}>{unqualifiedCount}</Text>
                    </View>
                    <View style={styles.resultBox}>
                        <Text style={styles.resultTitle}>报废</Text>
                        <Text style={styles.resultNumber}>{fatalCount}</Text>
                    </View>
                    <View style={styles.resultBox}>
                        <Text style={styles.resultTitle}>让步接收</Text>
                        <Text style={styles.resultNumber}>{acceptCount}</Text>
                    </View>
                </View>
                {/* 上传图片部分 */}
                {!isFinished && (
                    <View style={styles.uploadCard}>
                        <Text style={styles.uploadTitle}>上传图片</Text>
                        <View style={styles.imagesRow}>
                            {/* 显示已上传的图片（只显示当前卡片的） */}
                            {(uploadedImagesMap[item.id] || []).map((imageUri, index) => (
                                <View key={index} style={styles.imageItem}>
                                    <TouchableOpacity
                                        onPress={() => {
                                            setSelectedImage(imageUri);
                                            setImageModalVisible(true);
                                        }}
                                    >
                                        <Image source={{ uri: imageUri }} style={styles.uploadedImage} />
                                    </TouchableOpacity>
                                    <TouchableOpacity
                                        style={styles.removeImageButton}
                                        onPress={() => {
                                            setUploadedImagesMap(prev => {
                                                const newList = prev[item.id].filter((_, i) => i !== index);
                                                return { ...prev, [item.id]: newList };
                                            });
                                        }}
                                    >
                                        <Image source={xIcon} style={styles.removeImageIcon} />
                                    </TouchableOpacity>
                                </View>
                            ))}
                            {/* 上传按钮 */}
                            <TouchableOpacity style={styles.uploadArea} onPress={() => handleImageUpload(item.id)}>
                                <View style={styles.uploadIconContainer}>
                                    <Image source={xiangjiIcon} style={styles.uploadIcon} />
                                </View>
                                <Text style={styles.uploadText}>点击上传</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                )}
                {/* 确认按钮 */}
                {!isFinished && (
                    <TouchableOpacity style={styles.confirmButton} onPress={() => handleConfirm(item)}>
                        <Text style={styles.confirmButtonText}>确认</Text>
                    </TouchableOpacity>
                )}
                {/* 添加物料按钮 */}
                {!isFinished && (
                    <View style={styles.addMaterialSection}>
                        <TouchableOpacity
                            style={styles.addMaterialButton}
                            onPress={() => {
                                fetchDefectList();
                                setCurrentCardId(item.id);
                                setModalVisible(true);
                            }}
                        >
                            <Text style={styles.addMaterialText}>添加物料</Text>
                            <Image source={jiahao} style={styles.addIcon} />
                        </TouchableOpacity>
                    </View>
                )}
                {/* 已选择的物料列表（只显示当前卡片的） */}
                {!isFinished && selectedMaterialsMap[item.id]?.length > 0 && (
                    <View style={styles.selectedMaterialsSection}>
                        <Text style={styles.selectedMaterialsTitle}>已选择的物料：</Text>
                        {selectedMaterialsMap[item.id].map((material, index) => (
                            <View key={index} style={styles.selectedMaterialItem}>
                                <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                                    <View style={{ flex: 1 }}>
                                        <Text style={styles.selectedMaterialText}>
                                            物料编码：{material.materialCode}
                                        </Text>
                                        <Text style={styles.selectedMaterialText}>
                                            检验结果：{material.result === 1 ? '合格' : material.result === 2 ? '不合格' : material.result === 3 ? '报废' : '让步接收'}
                                        </Text>
                                        <Text style={styles.selectedMaterialText}>
                                            故障原因：{material.defectName}
                                        </Text>
                                    </View>
                                    <TouchableOpacity
                                        style={styles.removeMaterialButton}
                                        onPress={() => {
                                            setSelectedMaterialsMap(prev => {
                                                const newList = prev[item.id].filter((_, i) => i !== index);
                                                return { ...prev, [item.id]: newList };
                                            });
                                        }}
                                    >
                                        <Image source={xIcon} style={styles.removeMaterialIcon} />
                                    </TouchableOpacity>
                                </View>
                            </View>
                        ))}
                    </View>
                )}
            </View>
        );
    };

    return (
        <SafeAreaView style={styles.container}>
            <Header
                title="来料检详情"
                showBackButton={true}
                onNavigateToLogin={onNavigateToLogin}
                onBackPress={onBackPress}
            />

            {/* 列表内容 */}
            {loading ? (
                <View style={styles.loadingContainer}>
                    <ActivityIndicator size="large" color="#0076ff" />
                    <Text style={styles.loadingText}>加载中...</Text>
                </View>
            ) : (
                <FlatList
                    data={data}
                    keyExtractor={(item) => item.id}
                    renderItem={renderItem}
                    contentContainerStyle={styles.listContainer}
                    refreshControl={
                        <RefreshControl
                            refreshing={refreshing}
                            onRefresh={handleRefresh}
                            colors={['#0076ff']}
                            tintColor="#0076ff"
                        />
                    }
                    ListEmptyComponent={
                        <View style={styles.emptyContainer}>
                            <Text style={styles.emptyText}>暂无检验详情数据</Text>
                        </View>
                    }
                />
            )}

            {/* 添加物料模态框 */}
            <Modal visible={modalVisible} transparent={true} animationType="fade">
                <View style={styles.modalContainer}>
                    <View style={styles.modalContent}>
                        <Text style={styles.modalTitle}>添加物料</Text>

                        {/* 扫码输入区域 */}
                        <View style={styles.scanInputContainer}>
                            <TouchableOpacity
                                style={styles.scanIcon}
                                onPress={() => {
                                    console.log('扫码按钮被点击了');
                                    // 先关闭添加物料模态框，再打开扫码模态框
                                    setModalVisible(false);
                                    setTimeout(() => {
                                        setScanModalVisible(true);
                                    }, 100);
                                }}
                            >
                                <Image source={saoma} style={styles.scanIconImage} />
                            </TouchableOpacity>
                            <TextInput
                                style={styles.scanInput}
                                placeholder="请扫物料二维码"
                                placeholderTextColor="#999"
                                value={materialCode}
                                onChangeText={setMaterialCode}
                            />
                            {materialCode.length > 0 && (
                                <TouchableOpacity
                                    style={styles.clearButton}
                                    onPress={() => setMaterialCode('')}
                                >
                                    <Text style={styles.clearButtonText}>×</Text>
                                </TouchableOpacity>
                            )}
                        </View>

                        {/* 单选按钮 */}
                        <View style={styles.radioContainer}>
                            {[1, 2, 3, 5].map(val => (
                                <TouchableOpacity
                                    key={val}
                                    style={styles.radioOption}
                                    onPress={() => setSelectedResult(val)}
                                >
                                    <View style={[styles.radioButton, selectedResult === val && styles.radioButtonSelected]}>
                                        {selectedResult === val && <View style={styles.radioButtonInner} />}
                                    </View>
                                    <Text style={styles.radioText}>
                                        {val === 1 ? '合格' : val === 2 ? '不合格' : val === 3 ? '报废' : '让步接收'}
                                    </Text>
                                </TouchableOpacity>
                            ))}
                        </View>

                        {/* 故障原因 */}
                        {selectedResult !== 1 && (
                            <View style={[styles.faultReasonContainer, { paddingBottom: 0 }]}>
                                <View style={{ flexDirection: 'row', alignItems: 'center', borderBottomWidth: 1, borderBottomColor: '#eee', paddingBottom: 8 }}>
                                    <Text style={styles.faultReasonLabel}>{'故障原因'}</Text>
                                    <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end' }}>
                                        <Text style={[styles.defectText, { marginRight: 8 }]}>
                                            {selectedDefect ? defectList.find(d => d.id === selectedDefect)?.defect_name || '请选择' : '请选择'}
                                        </Text>
                                        <TouchableOpacity onPress={() => {
                                            // 先关闭添加物料模态框，再打开故障原因选择模态框
                                            setModalVisible(false);
                                            setTimeout(() => {
                                                setDefectSelectModalVisible(true);
                                            }, 100);
                                        }}>
                                            <Image source={jiahao} style={{ width: 24, height: 24 }} />
                                        </TouchableOpacity>
                                    </View>
                                </View>
                            </View>
                        )}

                        {/* 操作按钮 */}
                        <View style={styles.modalButtons}>
                            <TouchableOpacity
                                style={styles.cancelButton}
                                onPress={() => {
                                    setModalVisible(false);
                                    setMaterialCode('');
                                    setSelectedResult(1);
                                    setSelectedDefect('');
                                }}
                            >
                                <Text style={styles.cancelButtonText}>取消</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={styles.confirmModalButton}
                                onPress={handleModalConfirm}
                            >
                                <Text style={styles.confirmModalButtonText}>确定</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>

            {/* 扫码模态框 */}
            <Modal visible={scanModalVisible} animationType="slide">
                <CustomQRScanner
                    onRead={(data: string) => {
                        console.log('扫码成功:', data);
                        setScanModalVisible(false);
                        setMaterialCode(data);
                        // 扫码成功后重新打开添加物料模态框
                        setTimeout(() => {
                            setModalVisible(true);
                        }, 100);
                    }}
                    onClose={() => {
                        console.log('扫码模态框关闭');
                        setScanModalVisible(false);
                        // 关闭扫码模态框后重新打开添加物料模态框
                        setTimeout(() => {
                            setModalVisible(true);
                        }, 100);
                    }}
                />
            </Modal>

            {/* 图片全屏显示模态框 */}
            <Modal visible={imageModalVisible} transparent={true} animationType="fade">
                <View style={styles.imageModalContainer}>
                    <TouchableOpacity
                        style={styles.imageModalOverlay}
                        onPress={() => setImageModalVisible(false)}
                    >
                        <Image
                            source={{ uri: selectedImage }}
                            style={styles.fullScreenImage}
                            resizeMode="contain"
                        />
                    </TouchableOpacity>
                </View>
            </Modal>

            {/* 新增选择故障原因模态框 */}
            <Modal visible={defectSelectModalVisible} transparent={true} animationType="slide" onRequestClose={() => {
                setDefectSelectModalVisible(false);
                // 关闭故障原因选择模态框后重新打开添加物料模态框
                setTimeout(() => {
                    setModalVisible(true);
                }, 100);
            }}>
                <View style={{ flex: 1, backgroundColor: 'rgba(0,0,0,0.5)', justifyContent: 'flex-end' }}>
                    <View style={{ width: '100%', height: '80%', backgroundColor: '#fff', overflow: 'hidden' }}>
                        <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', paddingVertical: 10, borderBottomWidth: 1, borderBottomColor: '#eee', position: 'relative' }}>
                            <Text style={{ fontSize: 20, fontWeight: 'bold', color: '#333', textAlign: 'center', flex: 1 }}>请选择故障原因</Text>
                            <TouchableOpacity onPress={() => {
                                setDefectSelectModalVisible(false);
                                // 关闭故障原因选择模态框后重新打开添加物料模态框
                                setTimeout(() => {
                                    setModalVisible(true);
                                }, 100);
                            }} style={{ position: 'absolute', right: 4, top: 4, padding: 4 }}>
                                <Image source={require('../../../../assets/xx.png')} style={{ width: 24, height: 24 }} />
                            </TouchableOpacity>
                        </View>
                        <View style={{ flexDirection: 'row', alignItems: 'center', backgroundColor: '#f0f0f0', borderRadius: 8, paddingHorizontal: 10, paddingVertical: 8, margin: 10, marginBottom: 10, minHeight: 36 }}>
                            <Image source={require('../../../../assets/ss.png')} style={{ width: 20, height: 20, marginRight: 10 }} />
                            <TextInput
                                style={{ flex: 1, fontSize: 16, color: '#333', paddingVertical: 4 }}
                                placeholder="请输入关键词搜索"
                                placeholderTextColor="#999"
                                value={defectSearch}
                                onChangeText={setDefectSearch}
                            />
                        </View>
                        <ScrollView style={{ flex: 1, marginHorizontal: 20, marginTop: 10 }}>
                            {(defectList.filter(d => !defectSearch || d.defect_name.includes(defectSearch))).length > 0 ?
                                defectList.filter(d => !defectSearch || d.defect_name.includes(defectSearch)).map(defect => (
                                    <TouchableOpacity
                                        key={defect.id}
                                        style={{ paddingVertical: 12, borderBottomWidth: 1, borderBottomColor: '#eee' }}
                                        onPress={() => {
                                            setSelectedDefect(defect.id);
                                            setDefectSelectModalVisible(false);
                                            // 选择故障原因后重新打开添加物料模态框
                                            setTimeout(() => {
                                                setModalVisible(true);
                                            }, 100);
                                        }}
                                    >
                                        <Text style={{ fontSize: 16, color: '#333' }}>{defect.defect_name}</Text>
                                    </TouchableOpacity>
                                )) : (
                                    <Text style={{ textAlign: 'center', color: '#999', marginTop: 20 }}>暂无数据</Text>
                                )
                            }
                        </ScrollView>
                    </View>
                </View>
            </Modal>
        </SafeAreaView>
    );
};

const { width } = Dimensions.get('window');

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    listContainer: {
        padding: 10,
    },
    card: {
        backgroundColor: '#fff',
        borderRadius: 8,
        marginBottom: 12,
        padding: 15,
        shadowColor: '#000',
        shadowOpacity: 0.1,
        shadowRadius: 4,
        shadowOffset: { width: 0, height: 2 },
        elevation: 3,
    },
    inspectionDetails: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginBottom: 15,
    },
    detailColumn: {
        flex: 1,
        alignItems: 'center',
    },
    detailTitle: {
        fontSize: 14,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 5,
    },
    detailValue: {
        fontSize: 12,
        color: '#666',
        textAlign: 'center',
    },
    resultsContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginBottom: 15,
    },
    resultBox: {
        flex: 1,
        alignItems: 'center',
        padding: 10,
        backgroundColor: '#f8f9fa',
        borderRadius: 6,
        marginHorizontal: 2,
    },
    resultTitle: {
        fontSize: 12,
        color: '#666',
        marginBottom: 5,
    },
    resultNumber: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#ff4444',
    },
    uploadCard: {
        backgroundColor: '#fff',
        borderRadius: 10,
        marginBottom: 7,
        padding: 12,
        shadowColor: '#000',
        shadowOpacity: 0.04,
        shadowRadius: 4,
        shadowOffset: { width: 0, height: 2 },
        elevation: 2,
    },
    uploadTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 10,
        paddingBottom: 8,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    uploadArea: {
        width: 70,
        height: 70,
        backgroundColor: '#f5f5f5',
        borderRadius: 8,
        justifyContent: 'center',
        alignItems: 'center',
        borderWidth: 1,
        borderColor: '#e0e0e0',
        borderStyle: 'dashed',
    },
    uploadIconContainer: {
        justifyContent: 'center',
        alignItems: 'center',
        marginBottom: 8,
    },
    uploadIcon: {
        width: 32,
        height: 32,
        tintColor: '#999',
    },
    uploadText: {
        fontSize: 12,
        color: '#999',
    },
    imagesRow: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginTop: 10,
    },
    imageItem: {
        position: 'relative',
        marginRight: 10,
        marginBottom: 10,
    },
    uploadedImage: {
        width: 70,
        height: 70,
        borderRadius: 8,
    },
    removeImageButton: {
        position: 'absolute',
        top: 0,
        right: 0,
        width: 17,
        height: 17,
        justifyContent: 'center',
        alignItems: 'center',
    },
    removeImageIcon: {
        width: 16,
        height: 16,
    },
    addMaterialSection: {
        marginBottom: 0,
    },
    addMaterialButton: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: 12,
        backgroundColor: '#f8f9fa',
        borderRadius: 6,
        borderWidth: 1,
        borderColor: '#ddd',
    },
    addMaterialText: {
        fontSize: 14,
        color: '#333',
    },
    addIcon: {
        width: 20,
        height: 20,
    },
    confirmButton: {
        // marginTop: 7,
        marginBottom: 8,
        alignSelf: 'center',
        backgroundColor: '#0076ff',
        borderRadius: 10,
        paddingVertical: 10,
        width: '100%',
    },
    confirmButtonText: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
        textAlign: 'center',
    },
    loadingContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingVertical: 50,
    },
    loadingText: {
        marginTop: 10,
        fontSize: 16,
        color: '#666',
    },
    emptyContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingVertical: 50,
    },
    emptyText: {
        fontSize: 16,
        color: '#999',
    },
    imageModalContainer: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.9)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    imageModalOverlay: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        width: '100%',
        height: '100%',
    },
    fullScreenImage: {
        width: width,
        height: width,
    },
    // 模态框相关样式
    modalContainer: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    modalContent: {
        backgroundColor: '#fff',
        borderRadius: 20,
        padding: 20,
        width: width * 0.9,
        maxWidth: 400,
        // minHeight: 300,
    },
    modalTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#333',
        textAlign: 'center',
        marginBottom: 20,
    },
    scanInputContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 20,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
        paddingBottom: 10,
    },
    scanIcon: {
        marginRight: 10,
    },
    scanIconImage: {
        width: 24,
        height: 24,
    },
    scanInput: {
        flex: 1,
        fontSize: 16,
        color: '#333',
        paddingRight: 35,
    },
    clearButton: {
        position: 'absolute',
        right: 0,
        top: '50%',
        transform: [{ translateY: -15 }],
        justifyContent: 'center',
        alignItems: 'center',
        width: 30,
        height: 30,
    },
    clearButtonText: {
        color: '#999',
        fontSize: 18,
        fontWeight: 'bold',
        textAlign: 'center',
        lineHeight: Platform.OS === 'ios' ? undefined : 30,
    },
    radioContainer: {
        flexDirection: 'row',
        marginBottom: 7,
    },
    radioOption: {
        flexDirection: 'row',
        alignItems: 'center',
        marginRight: 7,
        marginBottom: 10,
    },
    radioButton: {
        width: 20,
        height: 20,
        borderRadius: 10,
        borderWidth: 2,
        borderColor: '#ccc',
        backgroundColor: 'transparent',
        marginRight: 8,
        justifyContent: 'center',
        alignItems: 'center',
    },
    radioButtonSelected: {
        borderColor: '#0076ff',
        backgroundColor: '#0076ff',
    },
    radioButtonInner: {
        width: 8,
        height: 8,
        borderRadius: 4,
        backgroundColor: '#fff',
    },
    radioText: {
        fontSize: 14,
        color: '#333',
    },
    faultReasonContainer: {
        marginBottom: 10,
        position: 'relative',
    },
    faultReasonLabel: {
        fontSize: 16,
        color: '#333',
    },
    defectSelector: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: 12,
        paddingHorizontal: 15,
        borderWidth: 1,
        borderColor: '#ddd',
        borderRadius: 8,
    },
    defectText: {
        fontSize: 16,
        color: '#333',
    },
    defectArrow: {
        width: 16,
        height: 16,
    },
    defectDropdown: {
        position: 'absolute',
        top: 77,
        left: 0,
        right: 0,
        backgroundColor: '#fff',
        borderRadius: 8,
        borderWidth: 1,
        borderColor: '#ddd',
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.15,
        shadowRadius: 6,
        elevation: 4,
        zIndex: 1000,
        maxHeight: 200,
    },
    defectOption: {
        paddingVertical: 12,
        paddingHorizontal: 15,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    defectOptionText: {
        fontSize: 16,
        color: '#333',
    },
    modalButtons: {
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    cancelButton: {
        flex: 1,
        backgroundColor: '#fff',
        borderWidth: 1,
        borderColor: '#0076ff',
        borderRadius: 6,
        padding: 12,
        marginRight: 10,
        alignItems: 'center',
    },
    cancelButtonText: {
        fontSize: 16,
        color: '#0076ff',
    },
    confirmModalButton: {
        flex: 1,
        backgroundColor: '#0076ff',
        borderRadius: 6,
        padding: 12,
        marginLeft: 10,
        alignItems: 'center',
    },
    confirmModalButtonText: {
        fontSize: 16,
        color: '#fff',
    },
    // 扫码器相关样式
    scannerContainer: {
        flex: 1,
        backgroundColor: '#000',
        justifyContent: 'center',
        alignItems: 'center',
    },
    scannerTitle: {
        fontSize: 18,
        color: '#fff',
        marginBottom: 32,
    },
    scannerCloseButton: {
        marginTop: 32,
    },
    scannerCloseText: {
        color: '#007AFF',
        fontSize: 18,
    },
    selectedMaterialsSection: {
        marginTop: 10,
        // marginBottom: 10,
        padding: 12,
        backgroundColor: '#f8f9fa',
        borderRadius: 6,
        borderWidth: 1,
        borderColor: '#ddd',
    },
    selectedMaterialsTitle: {
        fontSize: 14,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 8,
    },
    selectedMaterialItem: {
        padding: 8,
        backgroundColor: '#fff',
        borderRadius: 4,
        marginBottom: 6,
        borderWidth: 1,
        borderColor: '#eee',
    },
    selectedMaterialText: {
        fontSize: 12,
        color: '#666',
        marginBottom: 2,
    },
    removeMaterialButton: {
        width: 24,
        height: 24,
        justifyContent: 'center',
        alignItems: 'center',
        marginLeft: 8,
    },
    removeMaterialIcon: {
        width: 18,
        height: 18,
    },
});

export default IqcDetail; 